<?php
/**
 * Here is your custom functions.
 */

use app\admin\service\SettingsService;
use support\Container;
use support\Response;

if (!function_exists('halt')) {
    /**
     * 调试变量并且中断输出
     * @param mixed $vars 调试变量或者信息
     */
    function halt(...$vars)
    {
        dump(...$vars);
        throw new \lib\exception\HttpResponseException(new Response(200));
    }
}

if (!function_exists('make')) {
    /**
     * Build an entry of the container by its name.
     *
     * This method behave like get() except resolves the entry again every time.
     * For example if the entry is a class then a new instance will be created each time.
     *
     * This method makes the container behave like a factory.
     *
     * @template T
     * @param string|class-string<T> $name Entry name or a class name.
     * @param array $args
     * @param bool $newInstance
     * @return mixed|T
     */
    function make (string $name, array $args = [], bool $newInstance = false) {
        if (!$newInstance && Container::has($name)) {
            return Container::get($name);
        }
        return Container::make($name, $args);
    }
}

/**
 * json_encode 不转译中文
 * @param $value
 * @return string
 */
function cms_json_encode ($value): string {
    return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

/**
 * 路径拼接
 * @param string $parts 需要拼接的路径
 * @return string
 */
function cms_join_paths (...$parts): string {
    if (sizeof($parts) === 0) return '';
    $prefix = ($parts[0] === DIRECTORY_SEPARATOR) ? DIRECTORY_SEPARATOR : '';
    $processed = array_filter(array_map(function ($part) {
        return rtrim($part, DIRECTORY_SEPARATOR);
    }, $parts), function ($part) {
        return !empty($part);
    });
    return $prefix . implode(DIRECTORY_SEPARATOR, $processed);
}

/**
 * 关联数组按照某个键去重
 * @param array $array 原始数组
 * @param int|string $key 去重键
 */
function cms_assoc_array_unique (array $array, int|string $key) {
    return array_reduce($array, function ($arr, $item) use ($key) {
        if (empty($arr)) {
            return [$item];
        } else {
            $keys = array_column($arr, $key);
            if (!in_array($item[$key], $keys)) {
                $arr[] = $item;
            }
            return $arr;
        }
    }, []);
}

function cms_system_setting (string|array $key) {
    return make(SettingsService::class)->settingValue($key);
}
